//
//  SearchViewController.m
//  HimalayaMusic
//
//  Created by dllo on 16/1/13.
//  Copyright © 2016年 WXCLegendary. All rights reserved.
//

#import "SearchViewController.h"

@interface SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong)UISearchBar *searchBar;
@property (nonatomic, strong)NSMutableArray *fuzzySource;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)AccurateModel *accurateModel;
@property (nonatomic, strong)NSMutableArray *coulmnArray;
@property (nonatomic, strong)NSMutableArray *sectionNumArray;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.coulmnArray = [NSMutableArray array];
    self.sectionNumArray = [NSMutableArray array];
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, self.view.width - 30, 30)];
    [self.view addSubview:self.searchBar];
    self.searchBar.delegate = self;
//    self.searchBar.barStyle = UIBarStyleBlack;
    self.searchBar.searchBarStyle = UISearchBarStyleProminent;
    self.searchBar.placeholder = @"请输入搜索内容";
    self.searchBar.showsSearchResultsButton = YES;

    self.searchBar.tintColor = [UIColor clearColor];
    //添加搜索按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(self.searchBar.right, self.searchBar.top, 30, 30);
    button.backgroundColor = [UIColor blackColor];
    [button setTitle:@"搜索" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(getSearchData:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    self.fuzzySource = [NSMutableArray array];
    [self createTableView];
    
    
}

- (void)getSearchData:(UIButton *)sender {
    [self getAccurateData];
    
    
    
    
    
}

//searchbar动态监听搜索关键字

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self getSearchData];
}

- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 94, self.view.width, self.view.height - 94 - 49) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    [self.tableView registerClass:[SearchTableViewCell class] forCellReuseIdentifier:@"searchTableViewCellIdentifier"];
    [self.view addSubview:self.tableView];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (self.fuzzySource.count) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
        cell.textLabel.text = [self.fuzzySource[indexPath.row] keyword];
        if ([self.fuzzySource[indexPath.row] imgPath]) {
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[self.fuzzySource[indexPath.row] imgPath]]];
        }
        return cell;
    } else {
        SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchTableViewCellIdentifier"];
        if ([self.coulmnArray[indexPath.section] isEqualToString:@"专辑"]) {
            cell.albumModel = self.sectionNumArray[indexPath.section][indexPath.row];
        } else if ([self.coulmnArray[indexPath.section] isEqualToString:@"用户"]) {
            cell.userModel = self.sectionNumArray[indexPath.section][indexPath.row];
        } else if ([self.coulmnArray[indexPath.section] isEqualToString:@"声音"]) {
            cell.trackModel = self.sectionNumArray[indexPath.section][indexPath.row];
        }
        return cell;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.fuzzySource.count) {
        return self.fuzzySource.count;
    } else {
        NSArray *array = self.sectionNumArray[section];
        NSLog(@"%ld", array.count);
        
        return array.count;
    }
    
    
    
    
    
    
    
    
    return self.fuzzySource.count;
}

- (void)getAccurateData {
    
    /**
     *  精确搜索需要置空fuzzySource数组
     */
    
    [self.fuzzySource removeAllObjects];
    [self.sectionNumArray removeAllObjects];
    NSString *string = [NSString stringWithFormat:@"http://search.ximalaya.com/front/v1?device=android&core=all&kw=%@&page=1&rows=3&spellchecker=true", [self.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [WXCNetWorkTool getWithUrl:string parameter:nil httpHeader:nil responseType:ResponseTypeJson success:^(id result) {
        self.accurateModel = [[AccurateModel alloc] initWithDictionary:result];
        
        [self.tableView reloadData];
    } fail:^(NSError *error) {
        
        
    }];
    
    
}


- (void)getSearchData {
    [self.fuzzySource removeAllObjects];
    NSString *string = [NSString stringWithFormat:@"http://search.ximalaya.com/suggest?device=android&kw=%@", [self.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [WXCNetWorkTool getWithUrl:string parameter:nil httpHeader:nil responseType:ResponseTypeJson success:^(id result) {
        for (NSDictionary *dic in result[@"albumResultList"]) {
            FuzzySearchModel *fuzzyModel = [[FuzzySearchModel alloc] initWithDictionary:dic];
            [self.fuzzySource addObject:fuzzyModel];
        }
        for (NSDictionary *dic in result[@"queryResultList"]) {
            FuzzySearchModel *fuzzyModel = [[FuzzySearchModel alloc] initWithDictionary:dic];
            [self.fuzzySource addObject:fuzzyModel];
        
        }
        [self.tableView reloadData];
        
    } fail:^(NSError *error) {
        
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.fuzzySource.count) {
        [self.coulmnArray removeAllObjects];
        return 1;
        
    } else {
    
    NSInteger num = 0;
    if (self.accurateModel.albumArray.count) {
        [self.coulmnArray addObject:@"专辑"];
        [self.sectionNumArray addObject:self.accurateModel.albumArray];
        num++;
    }
    if (self.accurateModel.userArray.count) {
        [self.coulmnArray addObject:@"用户"];
        [self.sectionNumArray addObject:self.accurateModel.userArray];
        num++;
    }
    if (self.accurateModel.trackArray.count) {
        [self.coulmnArray addObject:@"声音"];
        [self.sectionNumArray addObject:self.accurateModel.trackArray];
        num++;
    }
    
    
    return num;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    if (self.fuzzySource.count) {
        return nil;
        
    } else {
        
        return self.coulmnArray[section];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.fuzzySource.count) {
        NSLog(@"模糊搜索");
    } else if (self.coulmnArray.count) {
        if ([self.coulmnArray[indexPath.section] isEqualToString:@"专辑"]) {
            AlbumViewController *albumVC = [[AlbumViewController alloc] init];
            albumVC.hotRecommendListModel = [[HotRecommendListModel alloc] init];
            NSArray *array = self.sectionNumArray[indexPath.section];
            albumVC.hotRecommendListModel.albumId = [array[indexPath.row] ids];
            [self.navigationController pushViewController:albumVC animated:YES];
        } else if ([self.coulmnArray[indexPath.section] isEqualToString:@"用户"]) {
            
            //用户界面
            
            
        } else if ([self.coulmnArray[indexPath.section] isEqualToString:@"声音"]) {
            
            //声音界面
            
            
            
            
        }
        
        
    }
    
    
}












- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
